

import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';

class InAppPurchaseManager {
  // 单例
  static final InAppPurchaseManager _instance = InAppPurchaseManager._internal();

  factory InAppPurchaseManager() {
    return _instance;
  }

  InAppPurchaseManager._internal();

  // 初始化方法
  Future<void> initialize() async {
    await FlutterInappPurchase.instance.initialize();
    // 监听购买更新
    FlutterInappPurchase.purchaseUpdated.listen((productItem) {
      _handlePurchase(productItem!);
    });
    // 处理错误
    FlutterInappPurchase.purchaseError.listen((error) {
      print('购买错误: $error');
    });
  }

  // 获取产品列表
  Future<List<IAPItem>> getProducts(List<String> productIds) async {
    try {
      List<IAPItem> items = await FlutterInappPurchase.instance.getProducts(productIds);
      return items;
    } catch (e) {
      print('获取产品列表时出错: $e');
      return [];
    }
  }

  // 购买产品
  Future<void> purchaseProduct(String productId) async {
    try {
      await checkPendingTransactions(); // 检查挂起的交易
      await FlutterInappPurchase.instance.requestPurchase(productId);
    } catch (e) {
      print('购买失败: $e');
    }
  }

  // 检查挂起交易
  Future<void> checkPendingTransactions() async {
    try {
      List<PurchasedItem>? pendingTransactions = await FlutterInappPurchase.instance.getPendingTransactionsIOS();
      for (var transaction in pendingTransactions!) {
        print('处理挂起交易: ${transaction.transactionId}');
        await FlutterInappPurchase.instance.finishTransaction(transaction);
      }
    } catch (e) {
      print('检查挂起交易时出错: $e');
    }
  }

  // 处理购买
  Future<void> _handlePurchase(PurchasedItem productItem) async {
    print('购买成功: ${productItem.productId}');
    // 在这里可以根据需要执行后续操作，例如更新用户的购买记录等
    try {
      await FlutterInappPurchase.instance.finishTransaction(productItem);
    } catch (e) {
      print('完成交易时出错: $e');
    }
  }
}